const Koa = require('koa')
const Router = require('@koa/router')
const json = require('koa-json')
const logger = require('koa-logger')
const serve = require('koa-static')
const views = require('koa-views')
const koaBody = require('koa-body')
const path = require('path') // 导入path包 用于拼接路径
const fs = require('fs')
const { replaceVersion, deleteFolder, updateListTemplate } = require('./func.js')

const app = new Koa()
app.use(json())
app.use(logger())
app.use(koaBody())

app.use(serve(path.join(__dirname, 'static')))

app.use(views('views', { map: { html: 'ejs' } }))

const router = new Router()

router.get('/', async (ctx, next) => {
  // await ctx.render('index', { data: '后台数据'})
  await ctx.render('index')
})

router.post('/create', async (ctx) => {
  // ctx.body = ctx.request.body
  const versionData = ctx.request.body
  let remarks = versionData.remarks.split('\n') // 以换行符来分割
  remarks = remarks.map((str, index) => `<li>${index + 1}、${str}</li>`)
  versionData.remarks = remarks.join('')

  const dir = path.join(__dirname, 'templates')
  const saveFolderPath = path.join(__dirname, 'versionFolder') // 这个目录用来存储新生成的版本文件
  if (fs.existsSync(saveFolderPath)) {
    // 先清空掉生成版本文件的文件夹
    deleteFolder(saveFolderPath)
  }
  if (!fs.existsSync(saveFolderPath)) {
    fs.mkdirSync(saveFolderPath)
  }

  const folders = fs.readdirSync(dir)
  if (folders.length > 0) {
    const promises = folders.map(
      (fold) =>
        new Promise((resolve, reject) => {
          return replaceVersion(path.join(dir, '/' + fold), fold, saveFolderPath, versionData).then(resolve, reject)
        })
    )
    await Promise.all(promises).then(
      (res) => {
        // 更新模板中的list.html文件
        updateListTemplate(dir, versionData)
        ctx.body = {
          code: 200,
          msg: '生成版本文件成功'
        }
      },
      (err) => {
        ctx.body = {
          code: -1,
          msg: '执行数据替换时出错了'
        }
      }
    )
  }
})

app.use(router.routes(), router.allowedMethods())

app.listen(8866, () => {
  console.log('server is running at http://localhost:8866')
})
